<!DOCTYPE html> 
<html>
  <head>
    <!--META-->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=0.75">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge">

    <!--CSS--> 
    <link rel="stylesheet" href="API/css/themes/default/jquery.mobile.min.css" />
    <link rel="stylesheet" href="API/css/datatables/css/jquery.dataTables.css"/> 
    <link rel="stylesheet" href="API/css/mycss.css" />
    <link rel="stylesheet" href="css/mycss.css" />

    <!--JS-->
    <script type="text/javascript" src="API/js/jquery.min.js"></script>
    <script type="text/javascript" src="API/js/jquery.mobile.min.js"></script>
    <script type="text/javascript" src="API/js/highcharts.js"></script>
    <script type="text/javascript" src="API/js/modules/exporting.js"></script>
    <script type="text/javascript" src="API/js/jquery.dataTables.min.js"></script>
    <script type="text/javascript" src="include/config.js"></script>
    <script type="text/javascript" src="API/js/fonctions.js"></script>
    <script type="text/javascript" src="js/fonctions.js"></script>

    <script type="text/javascript">
    checkMaintenance();
    checkAuthentification();
	
    ///////////////////
    //BLOCK VARIABLE GLOBAL
    ///////////////////
    var id_page = 1;
    var dispo = 0;
    var arrayPrio = new Array();

    ///////////////////
    //BLOCK FONCTIONS EVENEMENTS
    ///////////////////
    //A la construction de la page
    $(document).on('pageinit',function() {
        try {
            // Init commmun
            init_commun();

            // Init page
        } catch (er) {
            log(0, "ERROR(init_home):" + er.message);
        }
    });

    //Affichage de la page avant onload
    $(document).on('pageshow',function() {
        try {
            //show commmun
            show_commun();
        } catch (er) {
            log(0, "ERROR(show):" + er.message);
        }
    });

    //Fin chargement page
    function OnLoad() {
        try {
            chargerSuiviConso();
            chargerMetrics();
            messagesShow();
        } catch (er) {
            log(0, "ERROR(OnLoad):" + er.message);
        }
    }

    ///////////////////
    //BLOCK FONCTIONS METIER
    ///////////////////
    /**
     * chargerSuiviConso
     */
    function chargerSuiviConso(){
        try {
            var strhtml = "<IMG SRC=\"API/img/loading.gif\" ALT=\"Chargement\" TITLE=\"Chargement\">";
            $('#div_suiviConso').html(strhtml);
            var tabInput = { };
            callBD("phpsql/getRapportActiviteODA.php", "POST", "text", tabInput, "retourSuiviConso");            
        } catch (er) {
            log(0, "ERROR(chargerSuiviConso):" + er.message);
        }
    }
    
    /**
     * chargerMetrics
     */
    function chargerMetrics(){
        try {
            var strhtml = "<IMG SRC=\"API/img/loading.gif\" ALT=\"Chargement\" TITLE=\"Chargement\">";
            $('#div_metrics').html(strhtml);
            var tabInput = { };
            callBD("phpsql/getMetrics.php", "POST", "text", tabInput, "retourMetrics");            
        } catch (er) {
            log(0, "ERROR(chargerMetrics):" + er.message);
        }
    }
    
    /**
     * changePrio
     */
    function changePrio(p_id, p_objJS, p_old_value){
        try {
            $('#label_prio_'+p_id).text(p_objJS.value);
            var tmpDispo = dispo + (arrayPrio[p_id]-p_objJS.value);
            $('#dispo').text(tmpDispo);
        } catch (er) {
            log(0, "ERROR(changePrio):" + er.message);
        }
    }
    
    /**
     * onOut
     */
    function onOut(p_id, p_objJS, p_old_value){
        try {
            dispo = dispo + (arrayPrio[p_id]-p_objJS.value);
            arrayPrio[p_id] = parseInt(p_objJS.value);
            $('#dispo').text(dispo);
        } catch (er) {
            log(0, "ERROR(onOut):" + er.message);
        }
    }
    
    /**
     * calculeMetrics
     */
    function calculeMetrics(){
        try {
            var totalPrio = 0;
            for (var indice in arrayPrio){
                totalPrio += arrayPrio[indice];
                var tabInput = { id : indice, value : arrayPrio[indice] };
                var retour = callBD("phpsql/updatePrioMetrics.php", "GET", "text", tabInput, null, false);
            }
            var tabInput = { id : 0, value : totalPrio };
            var retour = callBD("phpsql/updatePrioMetrics.php", "GET", "text", tabInput, null, false);
            chargerMetrics();
        } catch (er) {
            log(0, "ERROR(calculeMetrics):" + er.message);
        }
    }
    
    /**
     * openPopUp
     */
    function openPopUp(p_id){
        try {
            var tabInput = { id : p_id };
            var retour = callBD("phpsql/getMetricsDetailsById.php", "POST", "text", tabInput, null, false);
            var json_retour = JSON.parse(retour);
            
            var valide = parseFloat(json_retour["data"]["metrics"]["data"][0]["valide"]);
            var velociteObj = parseFloat(json_retour["data"]["metrics"]["data"][0]["velociteObj"]);
            var reste = valide;
            var i = 0;
            var serieDataTheo = new Array();
            while (reste > 0)
            {
                var Data = [i,reste];
                i++;
                reste -= velociteObj;
                serieDataTheo[serieDataTheo.length] = Data;
            }
            
            var histoConso = json_retour["data"]["burn"]["data"];
            var serieDataReel = new Array();
            var reste = valide;
            var i = 0;
            for (var indice in histoConso){
                var Data = [i,reste];
                i++;
                reste -= parseFloat(histoConso[indice]["conso"]);
                serieDataReel[serieDataReel.length] = Data;
            }
            
            var retour = $('#div_detailProjet').highcharts({
                chart: {
                },
                title: {
                    text: 'Burn Down : '+json_retour["data"]["metrics"]["data"][0]["label"]
                },
                xAxis: {
                    tickPosition: 'inside'
                },
                yAxis: {
                    min:0
                },
                series: [
                    {
                        name: 'Théorique',
                        marker: {
                            enabled: false
                        },       
                        data: serieDataTheo        
                    },
                    {
                        name: 'Réel',        
                        data: serieDataReel        
                    }
                ]
            });
            
            var strhtml = "Date de début : "+getStrDateFrFromUs(json_retour["data"]["detailsRIA"]["data"][0]["minWorkDate"])+"<br>";
            strhtml += "Date d'attérissage théorique : "+getStrDateFrFromUs(json_retour["data"]["metrics"]["data"][0]["atterissage"])+"<br>";
            strhtml += "Velocité théorique : "+json_retour["data"]["metrics"]["data"][0]["velociteObj"]+" J/H/S<br>";
            strhtml += "Velocité réel moyenne : "+json_retour["data"]["detailsRIA"]["data"][0]["velociteConst"]+" J/H/S<br>";
            $('#div_detailsProjet').html(strhtml);
            
            $('#popup').popup('open', {transition : 'flip'});
        } catch (er) {
            log(0, "ERROR(openPopUp):" + er.message);
        }
    }
    
    /**
     * getRMetricsCsv
     */
    function getMetricsCsv(){
        try {
            var currentTime = new Date();
            currentTime.setDate(currentTime.getDate() - 7);
            var annee = currentTime.getFullYear();
            var mois = pad2(currentTime.getMonth()+1);
            var jour = pad2(currentTime.getDate());
            var strDate = annee+"_"+mois+"_"+jour;        
            
            window.location = "phpsql/getMetricsCSV.php?ctrl=ok&ODASortie=csv&ODAFilename=oda_metrics_"+strDate;         
        }
        catch (er) {
            log(0, "ERROR(getRMetricsCsv):" + er.message);
        }
    }

    ///////////////////
    //BLOCK FONCTIONS AFFICHAGE
    ///////////////////
    /**
     * retourSuiviConso
     * 
     * @param {array} p_retour
     */
    function retourSuiviConso(p_retour){
        try {
            var json_retour = JSON.parse(p_retour);
            if(json_retour["strErreur"] == ""){
                
                var regroup = new Array();
                regroup = getListValeurPourAttribut(json_retour["data"]["projets"]["data"],"projet");
                
                var cate = new Array();
                cate = getListValeurPourAttribut(json_retour["data"]["semaines"]["data"],"semaine");
                
                //Les colonnes
                var datas = new Array();
                for (var indice in cate) {
                    var subDatas = { name : cate[indice]};
                    subDatas.type = "column";
                    subDatas.data = new Array();
                    
                    var consoSemaines = json_retour["data"]["consoSemaines"]["data"];
                    for (var indice0 in consoSemaines) {
                        var projet = consoSemaines[indice0]["projet"];
                        var semaine = consoSemaines[indice0]["semaine"];
                        var charge = consoSemaines[indice0]["charge"];
                        if(semaine == cate[indice]){
                            subDatas.data[subDatas.data.length] = parseFloat(charge);
                        }
                    }
                    datas[datas.length] = subDatas;
                }
                
                //La ligne
                var valides = new Array();
                valides = getListValeurPourAttribut(json_retour["data"]["projets"]["data"],"valide");
                for (var indice in valides) {
                    valides[indice] = parseFloat(valides[indice]);
                    if (valides[indice] == 0){
                        valides[indice] = null;
                    }
                }
                datas[datas.length] = {
                    type: 'spline',
                    name: 'Validé',
                    data: valides,
                    dataLabels: {
                        enabled: true
                    }
                };
                
                //Le camenbert
                var pie = new Array();
                for (var indice in cate) {
                    var semaineConsoTotal = 0;
                    var consoSemaines = json_retour["data"]["consoSemaines"]["data"];
                    for (var indice0 in consoSemaines) {
                        var projet = consoSemaines[indice0]["projet"];
                        var semaine = consoSemaines[indice0]["semaine"];
                        var charge = consoSemaines[indice0]["charge"];
                        if(semaine == cate[indice]){
                            semaineConsoTotal += parseFloat(charge);
                        }
                    }
                    
                    pie[pie.length] = {
                        name: cate[indice],
                        y: semaineConsoTotal
                    };
                }
                
                datas[datas.length] = {
                    type: 'pie',
                    name: 'Total consommé',
                    data: pie,
                    center: ["115%", "25%"],
                    size: 100,
                    showInLegend: false,
                    dataLabels: {
                        enabled: true
                    }
                };
                
                var retour = $('#div_suiviConso').highcharts({
                    chart: {
                        marginBottom: 75,
                        marginRight: 300
                    },
                    legend: {
                        align: 'center',
                        verticalAlign: 'bottom'
                    },
                    title: {
                        text: 'Consommé par projets ODA'
                    },
                    xAxis: {
                        categories: regroup
                    },
                    yAxis: {
                        min: 0,
                        title: {
                            text: 'Total consommé'
                        },
                        stackLabels: {
                            enabled: true,
                            style: {
                                fontWeight: 'bold',
                                color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
                            }
                        }
                    },
                    tooltip: {
                        formatter: function() {
                            var s;
                            if (this.point.name) { // the pie chart
                                s = this.point.name +': '+ this.y +' J/H';
                            } else {
                                if(this.series.name != "Validé"){
                                    s = this.series.name +' : '+ this.y +' J/H';
                                }else{
                                    s = this.x +' : '+ this.y +' J/H';
                                }
                            }
                            return s;
                        }
                    },
                    plotOptions: {
                        column: {
                            stacking: 'normal',
                            dataLabels: {
                                enabled: true,
                                color: 'white',
                                formatter: function() {
                                    var s;
                                    if(this.y != 0){
                                        s = this.y;
                                    }
                                    return s;
                                }
                            }
                        },
                        pie: {
                            allowPointSelect: true,
                            cursor: 'pointer',
                            dataLabels: {
                                enabled: true,
                                color: '#000000',
                                connectorColor: '#000000',
                                format: '{point.name}:{point.y}j/h'
                            }
                        }
                    },
                    series: datas
                });
            } else{
                $('#div_suiviConso').html(json_retour["strErreur"]);
            }
        } catch (er) {
            log(0, "ERROR(retourSuiviConso):" + er.message);
        }
    }
    
    
    /**
     * retourMetrics
     * 
     * @param {array} p_retour
     */
    function retourMetrics(p_retour){
        try {
            var json_retour = JSON.parse(p_retour);
            var objDataTable = objDataTableFromJsonArray(json_retour["data"]["metrics"]["data"]);
            var strhtml = '<table width="60em" cellpadding="0" cellspacing="0" border="0" class="display" id="table_metrics"></table></br></br>';
            dispo = parseInt(json_retour["data"]["pipe"]["data"][0]["dispo"]);
            strhtml += "Bande passante disponible : <label id='dispo'>"+json_retour["data"]["pipe"]["data"][0]["dispo"]+"</label></br>";
            strhtml += '<a href="javascript:calculeMetrics();" data-role="button" data-inline="true" data-icon="arrow-r" data-mini="true" id="submit">Calcule</a></br>';
            $('#div_metrics').html(strhtml).trigger('create');

            var oTable = $('#table_metrics').dataTable( {
                    "oLanguage": {
                        "sUrl": "API/css/datatables/dataTables_I8N/lang_FR.json"
                    },
                    "sPaginationType": "full_numbers",
                    "aaData": objDataTable.data,
                    "aaSorting": [[1,'desc']],
                    "aoColumns": [
                        { sTitle: "Label", sClass: "left", sWidth: "20em" },
                        { sTitle: "Priorité", sClass: "center", sWidth: "5em" },
                        { sTitle: "Slide", sClass: "center", sWidth: "10em" },
                        { sTitle: "Validé", sClass: "center", sWidth: "5em" },
                        { sTitle: "Reste", sClass: "center", sWidth: "5em" },
                        { sTitle: "Projection", sClass: "center", sWidth: "5em" }
                    ],
                   aoColumnDefs: [
                        {//label
                            mRender: function ( data, type, row ) {
                                if ( type == 'display' ) {
                                    return '<a href="javascript:openPopUp('+row[0]+');">'+row[1]+'</a>';
                                }
                                return row[1];
                            },
                            aTargets: [ 0 ]
                        },
                        {//priorite
                            mRender: function ( data, type, row ) {
                                if ( type == 'display' ) {
                                    return '<label id="label_prio_'+row[0]+'">'+row[2]+'</label>';
                                }
                                return row[2];
                            },
                            aTargets: [ 1 ]
                        },
                        {//slide
                            mRender: function ( data, type, row ) {
                                if(row[0] != '0'){
                                    arrayPrio[row[0]] = parseInt(row[2]);
                                    return '<input type="range" name="slider-mini" id="slider-mini" value="'+row[2]+'" min="0" max="'+(parseInt(row[2])+dispo)+'" data-highlight="true" data-mini="true" onchange="changePrio('+row[0]+', this, '+parseInt(row[2])+')"  onblur="onOut('+row[0]+', this, '+parseInt(row[2])+');"/>';
                                }else{
                                    return '';
                                }
                            },
                            aTargets: [ 2 ]
                        },
                        {//valide
                            mRender: function ( data, type, row ) {
                                return row[3];
                            },
                            aTargets: [ 3 ]
                        },
                        {//reste
                            mRender: function ( data, type, row ) {
                                return row[4];
                            },
                            aTargets: [ 4 ]
                        },
                        {//atterissage
                            mRender: function ( data, type, row ) {
                                if ( type == 'display' ) {
                                    var str = "";
                                    if(row[7] != null){
                                        str = getStrDateFrFromUs(row[7]);
                                    }
                                    return str;
                                }
                                return row[7];
                            },
                            aTargets: [ 5 ]
                        }
                    ]
                });
        } catch (er) {
            log(0, "ERROR(retourMetrics):" + er.message);
        }
    }
</script>

</head>
<body onload="OnLoad();">

    <!-- page -->
    <div data-role="page" data-title="Titre">

        <!-- /panel -->
        <div data-role="panel" id="mypanel" data-display="overlay" data-position="left">

        </div>
        <!-- /panel -->

        <!-- header -->
        <div data-role="header" data-position="fixed">
            <a href="#mypanel" data-role="button" data-icon="home" data-iconpos="notext">home</a>
            <h1 id="id_titre">titre</h1>
            <a href="javascript:window.location = ('./page_contact.html?mili='+getMilise());" data-role="button" data-icon="info" data-iconpos="notext">Contact</a>
        </div>
        <!-- /header -->

        <!-- content -->
        <div data-role="content" id="main_content">
            
            <!-- PopUp -->
            <div data-role="popup" id="popup" data-theme="a" class="ui-corner-all">
                <div style="padding:10px 20px;width: 600px">
                    <h4>D&eacute;tails</h3>
                    <div id="div_detailProjet"></div>
                    <div id="div_detailsProjet"></div>
                    <a data-role="button" data-theme="b" data-icon="check" href="#" onclick="$('#popup').popup('close');">Ferm&eacute;</a>
                </div>
            </div>
            <!-- /PopUp -->
            
            <div data-role="collapsible" data-collapsed="false" data-mini="true">
                <h4>Le consommé sur les projets ODA</h3>
                <div id="div_suiviConso" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
            </div>
            <div data-role="collapsible" data-collapsed="false" data-mini="true">
                <h4>Metrics</h4>
                <div id="div_metrics"></div>
                <a href="javascript:getMetricsCsv();" data-role="button" data-inline="true" data-icon="arrow-r" data-mini="true">CSV Export</a>
            </div>
            <div id="notifcation" style="background-color:#f7931e;position:absolute;bottom:50px;width:97%;text-align:center;vertical-align:middle;line-height:normal;line-height:30px;height:30px;display:none"></div>		
        
        </div>
        <!-- /content -->

        <!-- footer -->
        <div data-role="footer" data-position="fixed">
            <a data-role="button" data-icon="search" data-iconpos="notext" class="ui-btn-left" href="javascript:window.location = ('./page_faq.html?mili='+getMilise());">FAQ</a>
            <h1 id="id_affichageUser">User</h1>
            <a data-role="button" data-icon="delete" data-iconpos="notext" class="ui-btn-right" href="javascript:window.location = ('./page_sortie.html?mili='+getMilise());">Logout</a>
        </div>
        <!-- /footer -->

    </div>
    <!-- /page -->
</body>
</html>